package
{
	import flash.geom.Point;
	
	import mx.collections.ArrayCollection;

	public class PointMesh extends ArrayCollection
	{
		/* size variables */
		private var initx:int = 71;		// default starting point of mesh
		private var inity:int = 92;		// default starting point of mesh
		private var totalw:int = 840;	// default total width of mesh
		private var h:int = 41;			// default height of each slot
		private var w:int;				// width of each slot
		
		/* time variables */
		private var startTime:Number;	// starting time
		private var endTime:Number;		// ending time
		
		/* constructor */
		public function PointMesh(source:Array=null)
		{
			super(source);
			
			setWidth();
			setTime(8.0, 17.0);
			
			for (var i:int = 0; i <= 5; i++)
			{
				addDay(i);
			}
		}
		
		/* set width of each column */
		public function setWidth():void
		{
			var numdays:int = this.length;
			w = totalw / numdays;
		}
		
		/* set time frame */
		public function setTime(start:Number, end:Number):void
		{
			startTime = start;
			endTime = end;
		}
		
		/* update point positions */
		public function updatePoints():void
		{
			setWidth();
			
			for each (var col:ArrayCollection in this)
			{
				for each (var p:Point in col)
				{
					var day:int = this.getItemIndex(col);
					var i:int = col.getItemIndex(p);
					var dx:int = initx + day*w - p.x;
					var dy:int = inity + i*h - p.y;
					p.offset(dx,dy);
				}
			}
		}
		
		/* get a point by day and time */
		public function getPoint(day:int, time:Number):Point
		{
			var col:ArrayCollection = this.getItemAt(day) as ArrayCollection;
			var index:int = (time-startTime)*2;
			return col.getItemAt(index) as Point;
		}
		
		/* add a column */
		public function addDay(day:int):void
		{
			/* add column */
			var col:ArrayCollection = new ArrayCollection();
			this.addItemAt(col, day)
			
			if (this.length >= 5)
			{
				updatePoints();
			}
			
			/* add points */
			var numPoints:int = (endTime-startTime)*2
			for (var i:int = 0; i < numPoints; i++)
			{
				var x:int = initx + day*w;
				var y:int = inity + i*h;
				var p:Point = new Point(x,y);
				col.addItem(p);
			}
		}
		
		/* remove a column */
		public function removeDay(day:int):void
		{
			this.removeItemAt(day);
			
			if (this.length >= 5)
			{
				updatePoints();
			}
		}
	}
}
